import { FC, useEffect, useRef, useState } from 'react';
import { ConfigProvider, Table, TableProps, Tooltip } from 'antd';
import { LocationInfo } from '#/entity.ts';
import { Page } from '#/api.ts';
import { useCurrentIndex, useLocationData, useSetTableIndex } from '@/store/locationStore.ts';
import { createStyles } from 'antd-style';
import { TableRef } from 'antd/es/table';

const useStyle = createStyles(({ css }) => {
  return {
    row: css`
      cursor: pointer;
      &.active {
        background: var(--ycx-primary-color);
      }
    `,
  };
});

type Props = {
  loading: boolean;
};

const LocationTable: FC<Props> = ({ loading }) => {
  const { styles } = useStyle();
  const locationData = useLocationData();
  const currentIndex = useCurrentIndex();
  const setTableIndex = useSetTableIndex();
  const tableRef = useRef<TableRef>(null);

  const [page, setPage] = useState<Page>({
    page: 1,
    limit: 10,
    order: 'id DESC',
  });

  const tableProps: TableProps<LocationInfo> = {
    size: 'small',
    dataSource: locationData,
    columns: [
      { title: '时间', dataIndex: 'deviceTime', width: 200 },
      {
        title: '经纬度',
        dataIndex: 'longitude',
        width: 200,
        render: (_value, record) => `${record.longitude},${record.latitude}`,
      },
      {
        title: '地理位置',
        dataIndex: 'address',
        width: 200,
        ellipsis: true,
        render: (value) => <Tooltip title={value}>{value}</Tooltip>,
      },
      { title: '病害报警', dataIndex: 'alarmDesc', width: 200, render: (value) => value ?? '-' },
    ],
    rowKey: 'id',
    pagination: {
      current: page.page,
      pageSize: page.limit,
      onChange: (page, pageSize) => setPage({ page: page, limit: pageSize, order: 'id DESC' }),
      showTotal: (total) => `共 ${total} 条数据`,
    },
    scroll: {
      y: 140,
    },
    loading: loading,
    rowClassName: (_record, index) => {
      if (index === currentIndex % page.limit) {
        return `${styles.row} active`;
      } else {
        return styles.row;
      }
    },
    onRow: (_record, index) => {
      return {
        onClick: () => {
          setTableIndex((page.page - 1) * 10 + index!);
        },
      };
    },
  };

  useEffect(() => {
    setPage({
      page: 1,
      limit: 10,
      order: 'id DESC',
    });
  }, [locationData]);

  useEffect(() => {
    const p = Math.floor(currentIndex / page.limit) + 1; // 页码（1 开始）
    const row = currentIndex % page.limit; // 行号（0 开始）

    tableRef.current?.scrollTo({
      index: row,
    });
    setPage({ ...page, page: p });
  }, [currentIndex, page.limit]);

  return (
    <>
      <ConfigProvider
        theme={{
          components: {
            Table: {
              rowHoverBg: 'rgba(76, 104, 255, 0.08)',
            },
          },
        }}
      >
        <Table {...tableProps} ref={tableRef} />
      </ConfigProvider>
    </>
  );
};

export default LocationTable;
